﻿using AnesSystem.Models;
using AnesSystem.Util;
using AnesSystem.ViewModels;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Windows;
using System.Xml.Linq;

namespace AnesSystem.Udp
{

    public class UDPHelper
    {

        #region Variables

        private const int PORT = 13;
        private Socket client;
        private List<string> listIps = new List<string>();
        private static UDPHelper instance;

        #endregion

        #region Constructor

        public UDPHelper()
        {
            try
            {
                client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                //IPAddress[] ips = Dns.GetHostEntry(Dns.GetHostName()).AddressList;
                //string ip = "";
                //foreach (var item in ips)
                //{
                //    if(item.AddressFamily== AddressFamily.InterNetwork)
                //    {
                //        //ip = "127.0.0.1";
                //        ip = "192.168.1.227";
                //        //ip = "10.8.0.14";
                //    }
                //}
                //获取本机IP，并且绑定到发送IP的端口
                client.Bind(new IPEndPoint(IPAddress.Any, 0));
            }
            catch (Exception e)
            {
                Common.LogHelper.Info(typeof(UDPHelper), e);
            }
        }

        #endregion

        #region Properties


        public static UDPHelper Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new UDPHelper();
                }
                return instance;
            }
        }

        #endregion

        #region 依赖属性

        #endregion

        #region Event

        public event EventHandler<UdpArgs> ReceivedMsg;

        #endregion

        #region Private Methods

        private long Zhuan(string ip)
        {
            IPAddress ipaddress = IPAddress.Parse(ip); byte[] addbuffer = ipaddress.GetAddressBytes(); Array.Reverse(addbuffer);
            return (long)System.BitConverter.ToUInt64(addbuffer, 0);
        }

        #endregion

        #region Public/Protected Methods
        /// <summary>
        /// 向服务器的端口发送数据报
        /// </summary>
        /// <param name="msg"></param>
        public void SendMsg2Server(string msg)
        {
            //        Common.LogHelper.Info(typeof(UDPHelper), "MSG is:\n" + msg);
            try
            {
                EndPoint point = new IPEndPoint(IPAddress.Parse(DataManager.Instance.CurrentHospital.Ip), 12125);
                //EndPoint point = new IPEndPoint(IPAddress.Parse("172.16.16.25"), 12125);
                //EndPoint point = new IPEndPoint(IPAddress.Parse("10.10.15.7"), 12125);
                client.SendTo(Encoding.UTF8.GetBytes(msg), point);
            }
            catch (Exception e)
            {
                Common.LogHelper.Error(typeof(UDPHelper), e);
            }
        }


        /// <summary>
        /// 向特定ip的主机的端口发送数据报
        /// </summary>
        /// <param name="msg"></param>
        public void SendMsg(string msg)
        {
            ////           Common.LogHelper.Info(typeof(UDPHelper), "MSG is:\n" + msg);
            try
            {
                listIps.Clear();
                //指定发送的IP和端口，用构造方法里绑定的client发送
                foreach (var item in UdpMangager.Instance.IpList)
                {
                    if (string.IsNullOrEmpty(item)) continue;
                    string[] others = item.Split('|');
                    if (string.IsNullOrEmpty(DataManager.Instance.CurRoom.Ips))
                    {
                        foreach (var other in others)
                        {
                            if (string.IsNullOrEmpty(other) || listIps.Contains(other)) continue;
                            EndPoint point = new IPEndPoint(IPAddress.Parse(other), 12125);
                            client.SendTo(Encoding.UTF8.GetBytes(msg), point);
                            listIps.Add(other);
                        }
                    }
                    else
                    {
                        string[] selfs = DataManager.Instance.CurRoom.Ips.Split('|');

                        foreach (var other in others)
                        {
                            bool isSend = true;
                            if (string.IsNullOrEmpty(other) || listIps.Contains(other)) continue;
                            foreach (var self in selfs)
                            {
                                if (self.Equals(other))
                                {
                                    isSend = false;
                                    break;
                                }
                            }
                            if (isSend)
                            {
                                EndPoint point = new IPEndPoint(IPAddress.Parse(other), 12125);

                                client.SendTo(Encoding.UTF8.GetBytes(msg), point);
                                listIps.Add(other);
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Common.LogHelper.Error(typeof(UDPHelper), e);
            }
        }

        public void ReceiveMsg(string result = "")
        {

            ////新建UdpClient，绑定12125端口，用来监听本机12125端口，接受所有IP的12125收到的UDP信号
            UdpClient client = new UdpClient(12125);
            IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
            while (true)
            {
                try
                {
                    Byte[] receiveBytes = client.Receive(ref RemoteIpEndPoint);
                    string returnData = Encoding.UTF8.GetString(receiveBytes);
                    ReceivedMsg?.Invoke(this, new UdpArgs(returnData));
                }
                catch (Exception e)
                {
                    Common.LogHelper.Info(typeof(UDPHelper), e);
                }
            }

        }

        #endregion

        #region EventHandlers

        #endregion
    }

}